package com.hengtiansoft.lfy.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @ClassName: FileUtil
 * @Description: 文件类
 * @author caijiajun
 * @date 2015年12月11日 下午3:40:36
 * 
 */
public class FileUtil {
    /**
     * 
     * 检测SD卡是否存在
     */
    public static boolean checkSDcard() {
        return Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState());
    }

    /**
     * 
     * 获取文件保存点
     */
    public static File getSaveFile(String fileNmae) {
        File file = null;
        try {
            file = new File(Environment.getExternalStorageDirectory()
                    .getCanonicalFile() + "/" + fileNmae);
        } catch (IOException e) {
        }
        return file;
    }

    /**
     * 
     * 从指定文件夹获取文件
     */
    public static File getSaveFile(String folder, String fileNmae) {
        File file = new File(getSavePath(folder), fileNmae);
        return file;
    }

    /**
     * 
     * 获取文件保存路径
     */
    public static String getSavePath(String folder) {
        return Environment.getExternalStorageDirectory() + "/" + folder;
    }

    // 从服务器下载apk
    public static File getFileFromServer(Context context, String urlPath,
                                         ProgressDialog pd, String apkName) throws Exception {
        // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        URL url = new URL(urlPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        // 获取到文件的大小
        pd.setMax(conn.getContentLength());
        InputStream is = conn.getInputStream();
        File file = null;
        File apkFile = null;
        if (hasSDCard()) {
            file = new File(getRootFilePath());
            if (!file.exists()) {
                file.mkdir();
            }
            apkFile = new File(getRootFilePath() + apkName);
        } else {
            file = new File(
                    "/storage/sdcard0/Android/data/com.hengtiansoft.lfy/");// com.hengtiansoft.lfy
            apkFile = new File(
                    "/storage/sdcard0/Android/data/com.hengtiansoft.lfy/"
                            + apkName);
            if (!file.exists()) {
                if (file.mkdir()) {
                    // apkFile = new File("/storage/sdcard0/" + apkName);
                } else {
                    file = new File(
                            "/storage/sdcard1/Android/data/com.hengtiansoft.lfy/");
                    apkFile = new File(
                            "/storage/sdcard1/Android/data/com.hengtiansoft.lfy/"
                                    + apkName);
                    if (!file.exists()) {
                        if (file.mkdir()) {
                            // apkFile = new File("/storage/sdcard1/" +
                            // apkName);
                        } else {
                            file = new File(
                                    "/storage/sdcard/Android/data/com.hengtiansoft.lfy/");
                            if (!file.exists()) {
                                // file.mkdir();
                                // fail:alert"请插入SD卡"
                                Toast.makeText(context, "请插入SD卡",
                                        Toast.LENGTH_LONG).show();
                            }
                            apkFile = new File(
                                    "/storage/sdcard/Android/data/com.hengtiansoft.lfy/"
                                            + apkName);
                        }
                    }
                }
            }
        }
        // Log.i("FileUtils", "<getFileFromServer> -- file = " + file);
        FileOutputStream fos = new FileOutputStream(apkFile);
        BufferedInputStream bis = new BufferedInputStream(is);
        byte[] buffer = new byte[1024];
        int len;
        int total = 0;
        while ((len = bis.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
            total += len;
            // 获取当前下载量
            pd.setProgress(total);
        }
        fos.close();
        bis.close();
        is.close();
        return apkFile;
    }

    public static String[] getVolumePaths(Context context) {
        StorageManager mStorageManager;
        Method mMethodGetPaths;
        mStorageManager = (StorageManager) context
                .getSystemService(Context.STORAGE_SERVICE);
        String[] paths = null;
        try {
            mMethodGetPaths = mStorageManager.getClass().getMethod(
                    "getVolumePaths");
            paths = (String[]) mMethodGetPaths.invoke(mStorageManager);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return paths;
    }

    public static String getVolumeState(Context context, String volumePath) {
        StorageManager mStorageManager;
        Method mMethodGetState;
        mStorageManager = (StorageManager) context
                .getSystemService(Context.STORAGE_SERVICE);
        String state = null;
        if (volumePath == null) {
            return null;
        }
        try {
            mMethodGetState = mStorageManager.getClass().getMethod(
                    "getVolumeState");
            state = (String) mMethodGetState
                    .invoke(mStorageManager, volumePath);
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (InvocationTargetException ex) {
            ex.printStackTrace();
        }
        return state;
    }

    public static boolean hasSDCard() {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED)) {
            return false;
        }
        return true;
    }
    /**
     * 获得指定文件的byte数组
     * sp
     * 2016年5月26日10:16:32
     */
    public static byte[] getBytes(String filePath){
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
    public static String getRootFilePath() {
        // if (hasSDCard()) {
        return Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/";// filePath:/sdcard/
        // } else {
        // // String dirPath =
        // return Environment.getDataDirectory().getAbsolutePath(); // filePath:
        // // /data/data/
        // }
    }
}
